<?php
/**
 * Created by PhpStorm.
 * User: 64423
 * Date: 2018/10/31
 * Time: 10:58
 */

namespace app\api\home;


class Address extends Common
{
    public function lists()
    {
        $user_id = input('get.user_id', 0);
        if(!$user_id){
            return _json(-401, '请先登录');
        }
        $address_list = db('address')->where('user_id',$user_id)->order('is_default desc,id desc')->select();
        $data = [
            'addressList' => $address_list
        ];
        return _json(0, '执行成功',$data);
    }

    public function detail()
    {
        $id = input('get.id', 0);
        $address = db('address')->where('id',$id)->find();
        if($address){
            return _json(0, '执行成功',['address'=>$address]);
        }else{
            return _json(-1, '未找到该地址');
        }
    }
    // 文章详情

    public function save()
    {
        $params = input('post.',[]);
        if(!$params){
            return _json(-1, '参数错误');
        }

        $data = [
            'user_id' => $params['user_id'],
            'user_name' => $params['user_name'],
            'tel_number' => $params['tel_number'],
            'province_name' => $params['province_name'],
            'city_name' => $params['city_name'],
            'county_name' => $params['county_name'],
            'detail_info' => $params['detail_info'],
            'is_default' => $params['is_default']
        ];
        // 如果它是默认就把其他地址去掉默认
        if($params['is_default']){
            db('address')->where('user_id',$params['user_id'])->update(['is_default'=>0]);
        }
        // 如果这是第一个地址，默认默认
        $count = db('address')->where('user_id',$params['user_id'])->count();
        if($count == 0){
            $data['is_default'] = 1;
        }
        if($params['id'] == 0){
            $res = db('address')->insert($data);
        }else{
            $res = db('address')->where('id',$params['id'])->update($data);
        }

        if($res >=0){
            return _json(0, '执行成功');
        }else{
            return _json(-1, '保存失败');
        }
    }

    public function delete()
    {
        $id = input('post.id',0);
        if(!$id){
            return _json(-1, '参数错误');
        }
        $res = db('address')->where('id',$id)->delete();
        if($res){
            return _json(0, '执行成功');
        }else{
            return _json(-1, '删除失败');
        }
    }
}